<template>
  <div>
    <div class="assign-role">
      <div class="my-tree">
        <el-tree ref="treeRef" node-key="id" :data="list" :props="{label:'name'}" show-checkbox check-strictly @node-click="handleNodeClick" />
      </div>
      <div>
        <el-button type="primary" round @click="onSubmit">确定</el-button>
        <el-button round @click="cancel">取消</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { transformListToTree2 } from '@/utils'
import { AssignPermissionRequest, getRoleDetailByIdRequest } from '@/api/user'
export default {
  name: 'VueHr85AssignPermission',
  props: {
    currentId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getPermission()
  },
  methods: {
    handleNodeClick() {},
    async onSubmit() {
      try {
        const res = await AssignPermissionRequest({
          id: this.currentId,
          permIds: this.$refs.treeRef.getCheckedKeys()
        })
        if (res.success) {
          this.cancel()
        } else {
          this.$message.error('获取权限列表失败')
        }
      } catch (error) {
        console.log('AssignPermissionRequest', error)
      }
    },
    cancel() {
      this.$emit('close')
    },
    async getPermission() {
      // 公司里面写代码try和catch都必写,业务成功也要写(找后端要请求成功的字段,前端好去封装请求)
      try {
        // 获取权限管理列表
        const res = await getPermissionList()
        // res.code === 10000 有些后端 通过code码 10000表示业务成功,非10000表示业务代码失败
        if (res.success) {
          this.list = res.data
          console.log('getPermissionList:', res)
          // 因为表格里面需要渲染 树形结构,需要将平铺数据转换为树形结构,带有children的书写,才能出现折叠按钮
          this.list = transformListToTree2(res.data, '0')
          console.log('转换为树形结构之后的数据', this.list)
        } else {
          this.$message.error('获取权限列表失败')
        }

        const res2 = await getRoleDetailByIdRequest(this.currentId)
        if (res2.success) {
          console.log(res2)
          this.$refs.treeRef.setCheckedKeys(res2.data?.permIds || [])
        } else {
          this.$message.error('获取权限列表失败')
        }
      } catch (error) {
        console.log('getPermissionList', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
